//
//  TWCorrelationViewController.swift
//  EyepetizerImitative
//
//  Created by 田伟 on 2017/3/24.
//  Copyright © 2017年 个人. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit

class TWCorrelationViewController: UIViewController {
    
    // MARK:- 属性
    var itemModel : TWItemModel?{
        didSet {
            guard let itemModel = itemModel else {
                return
            }
            let bgImage = itemModel.cover?.blurred
            bgImageStr = bgImage
            titleLabelText = itemModel.title
            tw_id = itemModel.id?.stringValue
        }
    }
    var bgImageStr : String?
    var titleLabelText : String?
    var tw_id : String?
    var correlationArray = [TWCorrelationModel]()
    var lastAnimationView : TWAnimationView?
    
    
    // MARK:- 懒加载
    fileprivate lazy var tableView : UITableView = UITableView()
    fileprivate lazy var bgImageView : UIImageView = UIImageView()
    fileprivate lazy var topView : UIView = UIView()
    fileprivate lazy var titleLabel : UILabel = UILabel()
    fileprivate lazy var closeButton : UIButton = UIButton()
    fileprivate lazy var lineView : UIView = UIView()

    // MARK:- 系统回调
    override func viewDidLoad() {
        super.viewDidLoad()
        loadCorrelationData()
        setupBgImageView()
        setupTableView()
        addTopView()
        acceptNotification()
    }
    override var prefersStatusBarHidden: Bool{
        return true
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK:- 请求数据
extension TWCorrelationViewController {
    fileprivate func loadCorrelationData(){
        let correlationUrl = "https://baobab.kaiyanapp.com/api/v3/video/\(tw_id!)/detail/related?_s=935fbb69b0f051eff330ca3b680d9aa8&f=iphone&net=wifi&p_product=EYEPETIZER_IOS&u=27e73f129dc6a90ed0b2da2cb1c8b3d14829761d&v=3.3.0&vc=2412"
        TWNetworkTool.shareInstance.loadCorrelationData(urlString: correlationUrl) { (result, error) in
            if error != nil {
                return
            }
            guard let result = result else {
                return
            }
            for item in result {
                let corrrlationModel = TWCorrelationModel(dict: item["data"] as! [String : AnyObject])
                self.correlationArray.append(corrrlationModel)
            }
            self.tableView.reloadData()
        }
    }
}

// MARK:- UI界面
extension TWCorrelationViewController {
    fileprivate func setupTableView(){
        tableView = UITableView(frame: CGRect(x: 0, y: 90, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 90), style: .plain)
        tableView.separatorStyle = .none
        tableView.backgroundColor = UIColor.clear
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UINib(nibName: "TWCorrelationCell", bundle: nil), forCellReuseIdentifier: CorrelationCell)
        view.addSubview(tableView)
        
        let footerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 150))
        footerView.backgroundColor = UIColor.clear
        tableView.tableFooterView = footerView
        let footerLabel = UILabel()
        footerLabel.text = "-The End-"
        footerLabel.textColor = UIColor.white
        footerLabel.font = UIFont(name: "Lobster 1.4", size: 14)
        footerLabel.sizeToFit()
        footerView.addSubview(footerLabel)
        footerLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(footerView)
            make.centerY.equalTo(footerView)
        }
    }
    fileprivate func setupBgImageView(){
        bgImageView.frame = UIScreen.main.bounds
        // 检查图片是否已经被缓存
        let image = SDImageCache.shared().imageFromMemoryCache(forKey: bgImageStr)
        if image == nil {
            bgImageView.sd_setImage(with: URL(string: bgImageStr!))
        } else {
            bgImageView.image = image
        }
        view.addSubview(bgImageView)
    }
    fileprivate func addTopView(){
        topView.frame = CGRect(x: 0, y: 20, width: UIScreen.main.bounds.width, height: 51)
        topView.backgroundColor = UIColor.clear
        view.addSubview(topView)
        closeButton.setImage(UIImage(named: "Action_down_44x44_"), for: .normal)
        closeButton.addTarget(self, action: #selector(closeButtonClick), for: .touchUpInside)
        topView.addSubview(closeButton)
        closeButton.snp.makeConstraints { (make) in
            make.right.equalTo(topView).offset(-20)
            make.centerY.equalTo(topView)
            make.width.height.equalTo(44)
        }
        titleLabel.text = titleLabelText
        titleLabel.textColor = UIColor.white
        titleLabel.textAlignment = .left
        titleLabel.font = UIFont.init(name: "FZLTZCHJW--GB1-0", size: 20)
        topView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalTo(topView)
            make.right.equalTo(topView).offset(-84) // 84=closeButton.width + margin(20) * 2
            make.left.equalTo(topView).offset(20)
        }
        lineView.backgroundColor = UIColor(white: 1, alpha: 0.5)
        topView.addSubview(lineView)
        lineView.snp.makeConstraints { (make) in
            make.left.right.equalTo(topView)
            make.height.equalTo(1)
            make.top.equalTo(71)
        }
    }
}

// MARK:- 监听点击
extension TWCorrelationViewController {
    @objc fileprivate func closeButtonClick(){
        dismiss(animated: false) {
            self.lastAnimationView?.isOpenCorrelation = false
            self.lastAnimationView?.halfBottom_ShowMoreButtonClick()
        }
    }
    @objc fileprivate func correlationCellDidSeleted(note : NSNotification){
//        let needDict = note.object! as! [String : AnyObject]
//        let allArray = needDict["allArray"] as! [TWItemModel]           // 拿到一组模型
//        let itemModel = needDict["itemModel"] as! TWItemModel           // 拿到当前选中的模型
//        // 打开页面
//        let pushView = UIViewController()
//        
//        lastAnimationView?.animationViewDelegate = self
// 
//        // 将视频模型字典传过去
//        lastAnimationView?.allArray = allArray
//        // 将当前的模型对象传过去
//        lastAnimationView?.itemModel = itemModel
//        pushView.view.addSubview(lastAnimationView!)
//        pushView.modalPresentationStyle = .custom
//        present(pushView, animated: true) { 
//            UIApplication.shared.keyWindow?.addSubview(pushView.view)
//        }
    }
}

// MARK:- 监听通知
extension TWCorrelationViewController {
    fileprivate func acceptNotification(){
        NotificationCenter.default.addObserver(self, selector: #selector(correlationCellDidSeleted(note:)), name: NSNotification.Name(rawValue: CorrelationCollectionViewCellDidSeleted), object: nil)
    }
}


// MARK:- ----代理方法----
extension TWCorrelationViewController : UITableViewDataSource, UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return correlationArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CorrelationCell, for: indexPath) as! TWCorrelationCell
        let model = correlationArray[indexPath.row]
        cell.correlationModel = model
        cell.correlationCellDelegate = self
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 280
    }
}

extension TWCorrelationViewController : TWCorrelationCellDelegate {
    func correlationCellAboutButtonDidClick(correlationModel: TWCorrelationModel) {
        let str = correlationModel.header?.title
        TWLog(message: str!)
    }
}

// MARK:- TWAnimationViewDelegate代理方法
extension TWCorrelationViewController : TWAnimationViewDelegate {
    func animationViewVideoPlayButtonClick(model: TWItemModel) {
        let videoPlayVc = TWVideoPlayerController()
        videoPlayVc.palyModel = model
        present(videoPlayVc, animated: true) {
            UIApplication.shared.keyWindow?.addSubview(videoPlayVc.view)
        }
    }
    func animationViewVideoHalfBottom_ShowMore(itemModel: TWItemModel) {
        let correlationViewController = TWCorrelationViewController()
        correlationViewController.itemModel = itemModel
        present(correlationViewController, animated: false) {
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                UIApplication.shared.keyWindow?.addSubview(correlationViewController.view)
            })
        }
    }
    func animationViewVideoHalfBottom_Hidden() {
        //        print("移动View关闭视图")
    }
    func didmissButtonDidClick() {
        dismiss(animated: true) {
            
        }
    }
}



